import { createRouter, createWebHistory } from 'vue-router'
import { message } from 'ant-design-vue'
import LoginPage from '../views/LoginPage.vue'
import NotFoundPage from '../views/NotFoundPage.vue'
import Layout from '../views/Layout.vue'
import ArchiveRegister from '../views/archive/ArchiveRegister.vue'
import ArchiveReview from '../views/archive/ArchiveReview.vue'
import ArchiveQuery from '../views/archive/ArchiveQuery.vue'
import ArchiveDelete from '../views/archive/ArchiveDelete.vue'
import SalaryStandardRegister from '../views/salary/SalaryStandardRegister.vue'
import SalaryStandardReview from '../views/salary/SalaryStandardReview.vue'
import SalaryStandardQuery from '../views/salary/SalaryStandardQuery.vue'
import SalaryStandardChange from '../views/salary/SalaryStandardChange.vue'
import SalaryPayRegister from '../views/salary/SalaryPayRegister.vue'
import SalaryPayReview from '../views/salary/SalaryPayReview.vue'
import SalaryPayQuery from '../views/salary/SalaryPayQuery.vue'
import OrganizationSetting from '../views/system/OrganizationSetting.vue'
import PositionSetting from '../views/system/PositionSetting.vue'
import RoleList from '../views/system/RoleList.vue'
import RoleDetail from '../views/system/RoleDetail.vue'

// 定义每个路由允许的角色
const routeRoles = {
  '/archive/register': ['人事专员'],
  '/archive/review': ['复核专员'],
  '/archive/query': ['人事专员', '部门经理', '普通员工'],
  '/archive/delete': ['人事专员'],
  '/salary/standard-register': ['薪酬专员'],
  '/salary/standard-review': ['复核专员'],
  '/salary/standard-query': ['薪酬专员', '复核专员', '部门经理'],
  '/salary/standard-change': ['薪酬专员'],
  '/salary/pay-register': ['薪酬专员'],
  '/salary/pay-review': ['复核专员'],
  '/salary/pay-query': ['薪酬专员', '复核专员', '部门经理', '普通员工'],
  '/system/organization': ['系统专员'],
  '/system/position': ['系统专员'],
  '/role': ['权限管理员'],
  '/role/:id': ['权限管理员'],
}

// 根据角色获取默认路由
function getDefaultRouteByRole(role) {
  const roleDefaultRoutes = {
    人事专员: '/archive/register',
    复核专员: '/archive/review',
    部门经理: '/archive/query',
    普通员工: '/archive/query',
    系统专员: '/system/organization',
    薪酬专员: '/salary/standard-register',
    权限管理员: '/role',
  }
  return roleDefaultRoutes[role] || '/archive/query'
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: LoginPage,
    },
    {
      path: '/archive',
      component: Layout,
      redirect: '/archive/query', // 默认重定向，实际会在路由守卫中处理
      children: [
        {
          path: 'register',
          name: 'archive-register',
          component: ArchiveRegister,
        },
        {
          path: 'review',
          name: 'archive-review',
          component: ArchiveReview,
        },
        {
          path: 'query',
          name: 'archive-query',
          component: ArchiveQuery,
        },
        {
          path: 'delete',
          name: 'archive-delete',
          component: ArchiveDelete,
        },
      ],
    },
    {
      path: '/salary',
      component: Layout,
      redirect: '/salary/standard-query', // 默认重定向，实际会在路由守卫中处理
      children: [
        {
          path: 'standard-register',
          name: 'salary-standard-register',
          component: SalaryStandardRegister,
        },
        {
          path: 'standard-review',
          name: 'salary-standard-review',
          component: SalaryStandardReview,
        },
        {
          path: 'standard-query',
          name: 'salary-standard-query',
          component: SalaryStandardQuery,
        },
        {
          path: 'standard-change',
          name: 'salary-standard-change',
          component: SalaryStandardChange,
        },
        {
          path: 'pay-register',
          name: 'salary-pay-register',
          component: SalaryPayRegister,
        },
        {
          path: 'pay-review',
          name: 'salary-pay-review',
          component: SalaryPayReview,
        },
        {
          path: 'pay-query',
          name: 'salary-pay-query',
          component: SalaryPayQuery,
        },
      ],
    },
    {
      path: '/system',
      component: Layout,
      redirect: '/system/organization',
      children: [
        {
          path: 'organization',
          name: 'system-organization',
          component: OrganizationSetting,
        },
        {
          path: 'position',
          name: 'system-position',
          component: PositionSetting,
        },
      ],
    },
    {
      path: '/role',
      component: Layout,
      redirect: '/role',
      children: [
        {
          path: '',
          name: 'role-list',
          component: RoleList,
        },
        {
          path: ':id',
          name: 'role-detail',
          component: RoleDetail,
        },
      ],
    },
    {
      path: '/404',
      name: 'not-found',
      component: NotFoundPage,
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'catch-all',
      component: NotFoundPage,
    },
  ],
})

// // 路由守卫：检查登录状态和角色权限
// router.beforeEach((to, from, next) => {
//   // 检查是否在浏览器环境
//   if (typeof window === 'undefined' || !window.sessionStorage) {
//     next()
//     return
//   }

//   const token = sessionStorage.getItem('token')
//   const userRole = sessionStorage.getItem('userRole')
//   const isLoginPage = to.path === '/' || to.name === 'home'
//   const isNotFoundPage = to.path === '/404' || to.name === 'not-found' || to.name === 'catch-all'

//   // 如果未登录且不是访问登录页，重定向到登录页
//   if (!token && !isLoginPage) {
//     next('/')
//     return
//   }

//   // 如果已登录且访问登录页，重定向到默认页面
//   if (token && isLoginPage) {
//     const defaultRoute = getDefaultRouteByRole(userRole)
//     next(defaultRoute)
//     return
//   }

//   // 如果已登录，检查角色权限
//   if (token && !isLoginPage && !isNotFoundPage) {
//     // 处理父路由的重定向
//     if (
//       to.path === '/archive' ||
//       to.path === '/salary' ||
//       to.path === '/system' ||
//       to.path === '/role'
//     ) {
//       if (to.path === '/archive') {
//         // 根据角色获取档案模块的默认路由
//         if (userRole === '人事专员') {
//           next('/archive/register')
//         } else if (userRole === '复核专员') {
//           next('/archive/review')
//         } else {
//           next('/archive/query')
//         }
//         return
//       } else if (to.path === '/salary') {
//         // 根据角色获取薪酬模块的默认路由
//         if (userRole === '薪酬专员') {
//           next('/salary/standard-register')
//         } else if (userRole === '复核专员') {
//           next('/salary/standard-review')
//         } else {
//           next('/salary/standard-query')
//         }
//         return
//       } else if (to.path === '/system') {
//         // 系统设置只有系统专员可以访问
//         if (userRole === '系统专员') {
//           next('/system/organization')
//         } else {
//           message.warning('您没有权限访问该页面')
//           next(getDefaultRouteByRole(userRole))
//         }
//         return
//       } else if (to.path === '/role') {
//         // 角色管理只有权限管理员可以访问
//         if (userRole === '权限管理员') {
//           next('/role')
//         } else {
//           message.warning('您没有权限访问该页面')
//           next(getDefaultRouteByRole(userRole))
//         }
//         return
//       }
//     }

//     // 检查动态路由（如 /role/:id）
//     let allowedRoles = routeRoles[to.path]
//     if (!allowedRoles && to.path.startsWith('/role/')) {
//       allowedRoles = routeRoles['/role/:id']
//     }

//     // 如果路由需要权限检查
//     if (allowedRoles) {
//       // 如果没有角色或角色不在允许列表中
//       if (!userRole || !allowedRoles.includes(userRole)) {
//         message.warning('您没有权限访问该页面')
//         // 重定向到该角色的默认页面
//         const defaultRoute = getDefaultRouteByRole(userRole)
//         next(defaultRoute)
//         return
//       }
//     }
//   }

//   next()
// })

export default router
